package com.dbb.trade.util;

import java.util.ArrayList;
import java.util.List;

public final class StringUtils {
	
	private StringUtils() {}
	/**
	 * HTML 关键字转换
	 * @param str
	 * @return
	 */
	public static String htmlspecialchars(String htmlStr) {
		String targetStr = htmlStr;
		targetStr = targetStr.replaceAll("&", "&amp;");
		targetStr = targetStr.replaceAll("<", "&lt;");
		targetStr = targetStr.replaceAll(">", "&gt;");
		targetStr = targetStr.replaceAll("\"", "&quot;");
		return targetStr;
	}
	
	/**
	 * 通过类名获取表名
	 * @param c
	 * @return
	 */
	public static String getTableName(Class clz) {
		String tableName = clz.getName().substring(clz.getName().lastIndexOf("."));
		return tableName.toUpperCase();
	}
	/**
	 * 将字符串拆分成数组
	 * @param str
	 * @param regex
	 * @return
	 */
	public static String[] getArrayFromString(String sourseStr, String regex) {
		String targetStr = sourseStr;
		if(targetStr == null ) {
			return null;
		}
		if(targetStr.startsWith(regex)) {
			targetStr = targetStr.substring(1);
		}
		if(targetStr.endsWith(regex)) {
			targetStr = targetStr.substring(0, targetStr.length() -1);
		}
		return targetStr.split(regex); 
	}
	
	/**
	 * 替换字符
	 * @param str
	 * @param regex
	 * @return
	 */
	public static String replaceAll(String sourseStr, String tragetstr, String... regex) {
		String result =  sourseStr;
		for(String reg : regex) {
			if(result.contains(reg)) {
				result = result.replaceAll(reg, tragetstr);
			}
		}
		return result;
	}
	
	/**
	 * 替换字符
	 * @param str
	 * @param regex
	 * @return
	 */
	public static List<String> getUnitListString(String str, String tragetstr, String... regex) {
		String s = replaceAll(str, tragetstr, regex);
		return getListFromString(s, tragetstr);
	}

	/**
	 * 将字符串拆分成列表
	 * @param str
	 * @param regex
	 * @return
	 */
	public static List<String> getListFromString(String sourseStr, String regex) {
		String targetStr = sourseStr;
		List<String> list = new ArrayList<String>();
		if(sourseStr.startsWith(regex)) {
			targetStr = targetStr.substring(1);
		}
		if(targetStr.endsWith(regex)) {
			targetStr = targetStr.substring(0, targetStr.length() -1);
		}
		String[] strs = targetStr.split(regex);
		for(String s : strs) {
			if(!list.contains(s)) {
				list.add(s);
			}
		}
		return list;
	}
}
